package com.ruoyi.collect.controller;

import com.ruoyi.collect.domain.CollectSite;
import com.ruoyi.collect.domain.CollectTask;
import com.ruoyi.collect.service.ICollectEngineService;
import com.ruoyi.collect.service.ICollectSiteService;
import com.ruoyi.collect.utils.ImageLocalizer;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 批量采集操作控制器
 *
 * @author ruoyi
 * @date 2025-11-07
 */
@RestController
@RequestMapping("/collect/batch")
public class CollectBatchController extends BaseController {

    @Autowired
    private ICollectSiteService collectSiteService;

    @Autowired
    private ICollectEngineService collectEngineService;

    @Autowired
    private ImageLocalizer imageLocalizer;

    /**
     * 批量采集所有站点
     */
    @PreAuthorize("@ss.hasPermi('collect:batch:all')")
    @Log(title = "批量采集", businessType = BusinessType.INSERT)
    @PostMapping("/collectAll")
    public AjaxResult collectAllSites() {
        // 查询所有正常状态的站点
        CollectSite query = new CollectSite();
        query.setStatus("0");
        List<CollectSite> siteList = collectSiteService.selectCollectSiteList(query);

        if (siteList == null || siteList.isEmpty()) {
            return error("没有可用的采集站点");
        }

        List<CollectTask> tasks = new ArrayList<>();
        int successCount = 0;
        int failCount = 0;

        for (CollectSite site : siteList) {
            try {
                CollectTask task = collectEngineService.collectAll(site.getSiteId());
                if (task != null) {
                    tasks.add(task);
                    successCount++;
                }
            } catch (Exception e) {
                logger.error("站点 {} 批量采集失败: {}", site.getSiteName(), e.getMessage());
                failCount++;
            }
        }

        return success("批量采集任务创建完成，成功: " + successCount + ", 失败: " + failCount);
    }

    /**
     * 批量采集最新数据
     */
    @PreAuthorize("@ss.hasPermi('collect:batch:recent')")
    @Log(title = "批量采集最新", businessType = BusinessType.INSERT)
    @PostMapping("/collectRecent")
    public AjaxResult collectRecentFromAllSites(@RequestParam(defaultValue = "24") Integer hours) {
        // 查询所有正常状态的站点
        CollectSite query = new CollectSite();
        query.setStatus("0");
        List<CollectSite> siteList = collectSiteService.selectCollectSiteList(query);

        if (siteList == null || siteList.isEmpty()) {
            return error("没有可用的采集站点");
        }

        List<CollectTask> tasks = new ArrayList<>();
        int successCount = 0;
        int failCount = 0;

        for (CollectSite site : siteList) {
            try {
                CollectTask task = collectEngineService.collectRecent(site.getSiteId(), hours);
                if (task != null) {
                    tasks.add(task);
                    successCount++;
                }
            } catch (Exception e) {
                logger.error("站点 {} 批量采集最新失败: {}", site.getSiteName(), e.getMessage());
                failCount++;
            }
        }

        return success("批量采集最新任务创建完成，成功: " + successCount + ", 失败: " + failCount);
    }

    /**
     * 批量采集指定站点
     */
    @PreAuthorize("@ss.hasPermi('collect:batch:sites')")
    @Log(title = "批量采集指定站点", businessType = BusinessType.INSERT)
    @PostMapping("/collectSites")
    public AjaxResult collectSpecificSites(@RequestBody Long[] siteIds,
                                          @RequestParam(defaultValue = "24") Integer hours) {
        if (siteIds == null || siteIds.length == 0) {
            return error("请选择要采集的站点");
        }

        List<CollectTask> tasks = new ArrayList<>();
        int successCount = 0;
        int failCount = 0;

        for (Long siteId : siteIds) {
            try {
                CollectTask task = collectEngineService.collectRecent(siteId, hours);
                if (task != null) {
                    tasks.add(task);
                    successCount++;
                }
            } catch (Exception e) {
                logger.error("站点ID {} 批量采集失败: {}", siteId, e.getMessage());
                failCount++;
            }
        }

        return success("批量采集任务创建完成，成功: " + successCount + ", 失败: " + failCount);
    }

    /**
     * 批量停止任务
     */
    @PreAuthorize("@ss.hasPermi('collect:batch:stop')")
    @Log(title = "批量停止任务", businessType = BusinessType.UPDATE)
    @PostMapping("/stopTasks")
    public AjaxResult stopTasks(@RequestBody Long[] taskIds) {
        if (taskIds == null || taskIds.length == 0) {
            return error("请选择要停止的任务");
        }

        int successCount = 0;
        int failCount = 0;

        for (Long taskId : taskIds) {
            try {
                boolean success = collectEngineService.stopTask(taskId);
                if (success) {
                    successCount++;
                } else {
                    failCount++;
                }
            } catch (Exception e) {
                logger.error("停止任务 {} 失败: {}", taskId, e.getMessage());
                failCount++;
            }
        }

        return success("批量停止完成，成功: " + successCount + ", 失败: " + failCount);
    }

    /**
     * 批量删除任务
     */
    @PreAuthorize("@ss.hasPermi('collect:batch:delete')")
    @Log(title = "批量删除任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteTasks/{taskIds}")
    public AjaxResult deleteTasks(@PathVariable Long[] taskIds) {
        if (taskIds == null || taskIds.length == 0) {
            return error("请选择要删除的任务");
        }

        // TODO: 实现批量删除逻辑
        return success("批量删除完成");
    }

    /**
     * 清理过期图片
     */
    @PreAuthorize("@ss.hasPermi('collect:batch:cleanImages')")
    @Log(title = "清理过期图片", businessType = BusinessType.CLEAN)
    @PostMapping("/cleanImages")
    public AjaxResult cleanExpiredImages(@RequestParam(defaultValue = "30") Integer days) {
        try {
            int count = imageLocalizer.cleanExpiredImages(days);
            return success("清理完成，删除了 " + count + " 个过期图片");
        } catch (Exception e) {
            logger.error("清理过期图片失败: {}", e.getMessage(), e);
            return error("清理失败: " + e.getMessage());
        }
    }

    /**
     * 获取批量操作统计
     */
    @PreAuthorize("@ss.hasPermi('collect:batch:statistics')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics() {
        // TODO: 实现统计逻辑
        return success();
    }
}